package star.cloud.asme.base.file.cosClient;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.transfer.MultipleFileUpload;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import star.cloud.asme.base.file.fileInfo.FileInfo;
import star.cloud.asme.base.utils.StringUtil;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

@SuppressWarnings("ALL")
@Service
@RequiredArgsConstructor
@Slf4j
public class CosClientServiceImpl implements CosClientService {

    private static final String region = "ap-nanjing";

    private static final String bucketName = "junxi-1259130257";

    private final TransferManager transferManager;

    private final COSClient cosClient;

    @Override
    public UploadResult uploadLocalFile() {
        // 对象键(Key)是对象在存储桶中的唯一标识。
        String key = "1.jpg";
        // 本地文件路径
        String localFilePath = "f://1.jpg";
        File localFile = new File(localFilePath);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        //用于对上传对象进行流量控制，单位：bit/s，默认不进行流量控制
        //traffic-limit needs to be between 819200 and 838860800
        putObjectRequest.setTrafficLimit(819200);
        // 设置存储类型（如有需要，不需要请忽略此行代码）, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);
        UploadResult uploadResult = null;
        try {
            Upload upload = transferManager.upload(putObjectRequest);
            uploadResult = upload.waitForUploadResult();
        } catch (CosClientException | InterruptedException e) {
            e.printStackTrace();
        }
        return uploadResult;
    }

    @Override
    public FileInfo uploadInputStream(FileInfo fileInfo, MultipartFile file) {
        String key = generateFileKey(file.getOriginalFilename());
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        PutObjectRequest putObjectRequest;
        try {
            putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(), objectMetadata);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);
        Upload upload = transferManager.upload(putObjectRequest);
        try {
            upload.waitForUploadResult();
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        }
        fileInfo.setFileKey(key);
        fileInfo.setSize(file.getSize());
        fileInfo.setRegion(region);
        fileInfo.setBucket(bucketName);
        fileInfo.setExtension(StringUtil.getExtensionName(Objects.requireNonNull(file.getOriginalFilename())));
        fileInfo.setUrl(cosClient.getObjectUrl(bucketName, key).toString());
        fileInfo.setName(file.getOriginalFilename());
        log.info("uploadInputStream完成");
        return fileInfo;
    }


    @Override
    public void deleteFile(FileInfo fileInfo) {
        cosClient.deleteObject(fileInfo.getBucket(), fileInfo.getFileKey());
    }

    @Override
    public String generateFileUrl(String key) {
        return cosClient.getObjectUrl(bucketName, key).toString();
    }

    @Override
    public String generateFileKey(String fileName) {
        LocalDateTime time = LocalDateTime.now();
        return time.getYear() + "/" +//
                time.getMonthValue() + "/" +//
                time.getDayOfMonth() + "/" +//
                UUID.randomUUID() + "/" +//
                fileName;
    }

    @Override
    public MultipleFileUpload uploadDirectory() {
        // 设置文件上传到 bucket 之后的前缀目录，设置为 “”，表示上传到 bucket 的根目录
        String cos_path = "/prefix";
        // 要上传的文件夹的绝对路径
        String dir_path = "f://img";
        // 是否递归上传目录下的子目录，如果是 true，子目录下的文件也会上传，且 cos 上会保持目录结构
        boolean recursive = true;
        MultipleFileUpload upload = null;
        try {
            upload = transferManager.uploadDirectory(bucketName, cos_path, new File(dir_path), recursive);
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        return upload;
    }


}